import sqlite3
from flask import render_template, request, redirect, url_for, flash, session
from . import web_bp
from models import create_login_log, get_db_connection

# 登录页面
@web_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        # 连接数据库验证用户
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute('SELECT * FROM users WHERE username=? AND password=?', (username, password))
        user = cursor.fetchone()
        conn.close()
        
        if user:
            session['user_id'] = user[0]
            session['username'] = user[1]
            
            # 记录登录日志
            create_login_log(user[0], user[1], request.remote_addr, request.headers.get('User-Agent'), 1, '登录成功')
            
            return redirect(url_for('web.index'))
        else:
            flash('用户名或密码错误')
            # 记录登录失败日志
            create_login_log(None, username, request.remote_addr, request.headers.get('User-Agent'), 0, '登录失败')
    
    return render_template('login.html')

# 登出
@web_bp.route('/logout')
def logout():
    if 'user_id' in session:
        # 记录登出日志
        create_login_log(session['user_id'], session['username'], request.remote_addr, 
                         request.headers.get('User-Agent'), 1, '用户登出')
    
    session.clear()
    return redirect(url_for('web.login'))